package org.lboot.llog.config;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.IThrowableProxy;
import ch.qos.logback.classic.spi.StackTraceElementProxy;
import ch.qos.logback.core.AppenderBase;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.File;

@Slf4j
public class ConsoleLogAppender extends AppenderBase<ILoggingEvent> {
    private String extractExceptionStack(IThrowableProxy throwableProxy) {
        StringBuilder builder = new StringBuilder();
        while (throwableProxy != null) {
            if (builder.length() > 0) {
                builder.append("\nCaused by: ");
            }
            builder.append(throwableProxy.getClassName())
                    .append(": ")
                    .append(throwableProxy.getMessage());
            for (StackTraceElementProxy element : throwableProxy.getStackTraceElementProxyArray()) {
                builder.append("\n\tat ").append(element.toString());
            }
            throwableProxy = throwableProxy.getCause();
        }
        return builder.toString();
    }
    @Override
    protected void append(ILoggingEvent eventObject) {
        IThrowableProxy throwableProxy = eventObject.getThrowableProxy();
        if (throwableProxy != null) {
            // 将异常信息记录下来
            String formattedMessage = extractExceptionStack(throwableProxy);
            // 获取当前的追踪ID
            // 获取请求IP
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            assert attributes != null;
            HttpServletRequest request = attributes.getRequest();
            String traceId = (String) request.getAttribute("trace-id");
            // 构建日志信息
            String currentPath = System.getProperty("user.dir");
            File logFile = FileUtil.touch( currentPath + File.separator + "logs" + File.separator + traceId+".log");
            FileUtil.appendString(formattedMessage,logFile,  CharsetUtil.CHARSET_UTF_8);
        }
    }
}
